package com.escape.wx.controller;

import com.escape.wx.handler.WxChatMsgFactory;
import com.escape.wx.handler.WxChatMsgHandler;
import com.escape.wx.utils.MessageUtil;
import com.escape.wx.utils.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import sun.security.provider.SHA;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Author: escape_zebra
 * @CreateTime: 2025-01-15  10:51
 * @Description: TODO
 * @Version: 1.0
 */
@RestController
@Slf4j
public class CallBackController {

    private final String token = "asdadsadfas";

    @Resource
    private WxChatMsgFactory wxChatMsgFactory;

    @RequestMapping("test")
    public String test(){
        return "test";
    }

    @GetMapping("callback")
    public String checkSignature(
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam("echostr") String echostr
            ){

        log.info("验签: signature:{}, timestamp:{}, nonce:{}, echostr:{}", signature, timestamp, nonce, echostr);

        String shaStr = SHA1.getSHA1(token, timestamp, nonce, "");

        if (signature.equals(shaStr)) {
            return echostr;
        }

        return "unknown";
    }

    // produces：正确接收 xml 形式参数
    @PostMapping(value = "callback", produces = "application/xml;charset=UTF-8")
    public String checkSignature(
            // 用户消息体存放在 requestBody 中
            @RequestBody String requestBody,
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            // 加密模式
            @RequestParam(value = "msg_signature", required = false) String msgSignature
    ){

        log.info("接收到的微信的请求: requestBody: {}, signature:{}, timestamp:{}, nonce:{}",requestBody, signature, timestamp, nonce);

        Map<String, String> requestMap = MessageUtil.parseXml(requestBody);
        String msgType = requestMap.get("MsgType");
        String event = requestMap.get("Event");
        StringBuilder stringBuilder = new StringBuilder();
        log.info("msgType: {}, event: {}", msgType, event);
        stringBuilder.append(msgType);
        if (!StringUtils.isBlank(event)) {
            stringBuilder.append(".");
            stringBuilder.append(event);
        }
        String typeStr = stringBuilder.toString();

        WxChatMsgHandler wxChatMsgHandler = wxChatMsgFactory.getWxChatMsgHandler(typeStr);
        return wxChatMsgHandler.dealMsg(requestMap);
    }

}